<template>
    <el-card>
        <!-- 路径导航 -->
        <div slot="header">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }"> <i class="el-icon-house"></i> 首页</el-breadcrumb-item>
                <el-breadcrumb-item>商品管理</el-breadcrumb-item>
                <el-breadcrumb-item>分类参数</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <!-- 内容区域 -->
        <!-- 提示框 -->
        <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon></el-alert>
        <!-- 选择商品分类 -->
        <div class="line-cate">
            <span>请选择商品分类：</span>
            <el-cascader 
                :options="cateAllList"  
                v-model="cateId"
                clearable
                @change="getParamsList"
                :props="{ label:'cat_name', value:'cat_id' }"
            >
            </el-cascader>
        </div>
         <!-- 标签页 -->
         <!-- v-model 绑定的变量和 name的 值对应上了，那么就让这个tab展示 -->
         <el-tabs v-model="tabActiveName" @tab-click="getParamsList">
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled="isBtnDisable" @click="dialogShow=true" size="default">添加动态参数</el-button>
                <br> <br>
                <!-- 动态参数表格 -->
                <el-table :data="manyList" border >
                    <el-table-column type="expand" width="120">
                        <!-- 折叠列 -->
                        <!-- 参数值渲染 -->
                        <template slot-scope="scope">
                            <!-- 标签 -->
                            <el-tag
                                :key="tag"
                                v-for="(tag,idx) in scope.row.attr_vals"
                                closable
                                @close="handleClose(scope.row,idx)"
                                :disable-transitions="false"
                                >
                                {{tag}}
                            </el-tag>
                            <!-- 输入框 -->
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                ref="saveTagInput"
                                size="small"
                            >
                            </el-input>
                            <!-- 添加按钮 -->
                            <el-button v-else class="button-new-tag" size="small" type="primary" @click="showInput(scope.row)">+ 增加</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="序号" width="100"></el-table-column>
                    <el-table-column label="参数名" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="success" icon="el-icon-edit" @click="editAttr(scope.row)" size="small" circle></el-button>
                            <el-button type="danger" icon="el-icon-delete" @click="delAttr(scope.row)" size="small" circle></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" :disabled="isBtnDisable" @click="dialogShow=true" size="default">添加静态属性</el-button>
                <br><br>
                <!-- 静态属性表格 -->
                <el-table :data="onlyList" border >
                    <el-table-column type="expand" width="120">
                        <template slot-scope="scope">
                            <!-- 标签 -->
                            <el-tag
                                :key="tag"
                                v-for="(tag,idx) in scope.row.attr_vals"
                                closable
                                @close="handleClose(scope.row,idx)"
                                :disable-transitions="false"
                                >
                                {{tag}}
                            </el-tag>
                            <!-- 输入框 -->
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                ref="saveTagInput"
                                size="small"
                            >
                            </el-input>
                            <!-- 添加按钮 -->
                            <el-button v-else class="button-new-tag" size="small" type="primary" @click="showInput(scope.row)">+ 增加</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="序号" width="100"></el-table-column>
                    <el-table-column label="参数名" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="success" icon="el-icon-edit" @click="editAttr(scope.row)" size="small" circle></el-button>
                            <el-button type="danger" icon="el-icon-delete" @click="delAttr(scope.row)" size="small" circle></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
        
        <!--  添加 修改 参数弹框 -->
        <el-dialog
            :title="isAdd ?  tabActiveName==='many' ?  '添加动态参数':'添加静态属性'  : 
                            tabActiveName==='many' ? '修改动态参数':'修改静态属性'  "
            :visible.sync="dialogShow"
            width="40%"
            @close="form.attr_name=''"
           >
            <el-form v-if="dialogShow" :model="form" ref="form" :rules="formRules" label-width="120px" >
                <el-form-item :label=" tabActiveName==='many' ? '动态参数名':'静态属性名' " prop="attr_name">
                    <el-input v-model="form.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="dialogShow = false">取消</el-button>
                <el-button type="primary" @click="submit">提交</el-button>
            </span>
        </el-dialog>
        
    </el-card>
</template>

<script>
    export default {
        data() {
            return {
                cateAllList: [],  // 所有商品分类信息
                tabActiveName:'many',
                cateId:[],  // 选择的分类ID
                isBtnDisable:true, // 添加按钮是否启用
                onlyList:[],  // 静态属性列表
                manyList:[],   // 动态参数列表
                isAdd:true,     // 是否为添加行为
                dialogShow:false, // 弹框是否打开
                form:{
                    attr_name:''
                },
                formRules:{
                    attr_name:[
                        { required:true, message:'请输入内容', trigger:'blur' }
                    ]
                },
                editAttrId:null // 修改的属性ID
            }
        },
        created () {
            this.getAllCateList()
        },
        methods: {
            // 获取所有分类数据
             async getAllCateList() {
                // 1.请求发送
                let { data:res } = await this.$axios.get('categories')
                // 2.错误处理
                if( res.meta.status !== 200 ) return this.$message.error('数据请求出错')
                // 3.赋值数据
                this.cateAllList = res.data
            },
            // 获取静态、动态数据的方法
            async getParamsList(){
                // 监听分类ID数组长度是不是为3，如果是3说明选择了3级ID，要去请求数据了！
                if(this.cateId.length !== 3){
                    // 清空列表
                    this.onlyList = this.manyList = []
                    // 按钮禁用
                    this.isBtnDisable = true
                    // 跳出
                    return
                }

                this.isBtnDisable = false  // 添加按钮打开
                let id = this.cateId[2]
                let { data:res } = await this.$axios.get(`categories/${id}/attributes`,{
                    params:{
                        sel:this.tabActiveName
                    }
                })
                if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                // 对数据进行处理！
                res.data.forEach(item=>{
                    // 处理字符串分隔成数组
                    item.attr_vals = item.attr_vals.length === 0  ?  [] : item.attr_vals.split(',')
                    // 增加布尔变量控制输入框、按钮切换
                    item.inputVisible = false
                    // 增加一个变量用于绑定输入框的值
                    item.inputValue = ''
                })
                // 赋给对应的变量！
                this[this.tabActiveName+'List'] = res.data
            },
            // 修改属性
            editAttr(row){
                // 赋给修改ID数据
                this.editAttrId = row.attr_id
                // 回显表单数据
                this.form.attr_name = row.attr_name
                // 打开弹框
                this.dialogShow = true;
                // 修改isAdd
                this.isAdd = false
            },
            // 删除属性
            async delAttr(row){
                //  属性ID【row.attr_id】、 分类ID 【this.cateId[2]】
                try {
                    // 确认弹框
                     await this.$confirm('确定删除吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                    // 发送请求删除数据
                    let cat_id = this.cateId[2]
                    let { data:res } = await this.$axios.delete(`categories/${cat_id}/attributes/${row.attr_id}`)
                    // 错误处理
                    if(res.meta.status !==200 ) return this.$message.error(res.meta.msg)
                    // 成功弹框
                    this.$message.success(res.meta.msg)
                    // 拉取列表
                    this.getParamsList()
                } catch (error) {
                    this.$message.info('取消删除')
                }
            },
            // 添加、修改 的提交事件
            submit(){
                // 验证！
                this.$refs.form.validate(async valid=>{
                    if(!valid) return
                    // 判断添加还是修改行为！处理路径和请求方式问题
                    let cat_id = this.cateId[2]
                    let method,url
                    if(this.isAdd){
                        url = `categories/${cat_id}/attributes`
                        method = 'post'
                    }else{
                        url = `categories/${cat_id}/attributes/${this.editAttrId}`
                        method = 'put'
                    }
                    // 发送请求
                    let { data:res } = await this.$axios({
                        url,
                        method,
                        data:{
                            attr_name:this.form.attr_name,
                            attr_sel:this.tabActiveName
                        }
                    })
                    // 错误处理
                    if(![200,201].includes(res.meta.status)) return this.$message.error(res.meta.msg)
                    // 成功处理弹框提示
                    this.$message.success(res.meta.msg)
                    // 弹框关闭
                    this.dialogShow = false
                    // 将行为重置为增加
                    this.isAdd = true
                    // 重新拉取列表
                    this.getParamsList()
                })
            },
            // 打开输入框
            showInput(row){
                // 改变这一行的展示输入框变量
                row.inputVisible = true
                // this.$nextTick( ()=>{ ...  } ) 等到渲染之后做函数里面的事情
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                })
            },
            // 输入框失去焦点
            async handleInputConfirm(row){
                // 判断输入框绑定的变量是否有值，有值就要做添加事件和关闭、没有值就做关闭
                if(row.inputValue){
                    // 添加属性值， 但是确实修改参数！
                    let cat_id = this.cateId[2]
                     // 属性值要求是完整的所有内容，而不是这一次的数据！ 需要将这一次的数据放入到所有的数据里面，再将所有数据提交！
                    let attr_vals_all =  [...row.attr_vals,row.inputValue]
                    let { data:res } = await this.$axios.put(`categories/${cat_id}/attributes/${row.attr_id}`,{
                        attr_name:row.attr_name,
                        attr_sel:this.tabActiveName,
                        attr_vals:attr_vals_all.join(",")
                    })
                    if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    this.$message.success('添加成功')
                    // 将增加的数据放入到数组中
                    row.attr_vals.push(row.inputValue)
                }
                row.inputVisible = false
                row.inputValue = ''
            },
            // 标签的删除事件
            async handleClose(row,index){
                try {
                    await this.$confirm('确认删除吗？','提示',{
                        confirmButtonText:'确定',
                        cancelButtonText:'取消'
                    })
                    let attr_vals_old = [...row.attr_vals]
                    // 获取删除该元素以后的数组，把数组变成字符串，去修改提交！
                    attr_vals_old.splice(index,1)
                    let cat_id = this.cateId[2]
                    let { data:res } = await this.$axios.put(`categories/${cat_id}/attributes/${row.attr_id}`,{
                        attr_name:row.attr_name,
                        attr_sel:this.tabActiveName,
                        attr_vals:attr_vals_old.join(",")
                    })
                    if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    this.$message.success('删除成功')
                    row.attr_vals.splice(index,1)
                } catch (error) {
                    this.$message.info('取消删除')
                }
            }
        },
    }
</script>

<style lang="less" scoped>
.line-cate{
    margin:20px 0;
}
.el-tag{
    margin-right: 10px;
    margin-bottom: 10px;
}
.input-new-tag{
     width: 90px;
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
</style>